
/**
 *  特性
    暴露get方法
    暴露post方法
    post自定义contentType
    增加配置文件
    token定义
    添加判断状态，记录异常信息
    增加异常错误logError日志
    增加统一日志上报
 */
import {hex_md5}  from  './md5';
import Taro  from '@tarojs/taro'
import { HTTP_STATUS }  from '../constants/status'
import { requestBase } from '../config/config'
import { logError } from '../util/index'
// 获取访问token
function get_access_token()
{
    let date  = new Date();
    let year  = date.getFullYear();
    let month = date.getMonth()+1;
    let day   = date.getDate();
    month = month >= 10 ? month : '0' +month;
    day = day >= 10 ? day : '0' +day;
    // 今日日期
    let time = year+''+month+''+day;
    return hex_md5('OneBase' + time + 'l2V|gfZp{8`;jzR~6Y1_');
}
export default {
    baseOptions(params, method = 'GET') {
        let { url, data } = params
        let base = requestBase;
        let contentType = 'application/x-www-form-urlencoded'
        contentType = params.contentType || contentType
        const user_token = Taro.getStorageSync('user_token');
        const option = {
            isShowLoading: false,
            loadingText: '正在加载',
            url: base + url,
            data: data,
            method: method,
            header: { 'content-type': contentType, 'Global-User-Token': user_token,'Global-Access-Token': get_access_token() }, // 默认contentType ,预留token
            success(res) {
                if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
                    return logError('api', '请求资源不存在')
                    } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
                    return logError('api', '服务端出现了问题')
                    } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
                    return logError('api', '没有权限访问')
                    } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
                    return res.data
                }
            },
            error(e) {
                logError('api', '请求接口出现问题', e)
            }
        }
        return Taro.request(option)
    },
    get(url, data = '') {
        let option = { url, data }
        return this.baseOptions(option)
    },
    post(url, data, contentType) {
        let params = { url, data, contentType }
        return this.baseOptions(params, 'POST')
    }
}
